package cn.edu.sdjzu.xg.eagle.dao;



import cn.edu.sdjzu.xg.eagle.entity.Pagination;
import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BysjException;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.TreeSet;

/**
 * @author tg.si@188.com
 * @project xg22
 * @date 2025/3/15
 */
public class SchoolDaoImpl implements SchoolDaoInterface {
    static private SchoolDaoInterface schoolDaoImpl = null;
    public SchoolDaoImpl(){}

    public static SchoolDaoInterface getInstance(){
        if (schoolDaoImpl == null) {
            schoolDaoImpl = new SchoolDaoImpl();
            System.out.println("Create SchoolDaoImpl Object");
        }
        return schoolDaoImpl;
    }

    @Override
    public School find(Long id) throws SQLException, BysjException {
        System.out.println("[DEBUG] 开始查询，ID=" + id);

        Connection connection = null;
        try {
            connection = JdbcHelper.getConn();
            System.out.println("[DEBUG] 获取连接: " + (connection != null ? "成功" : "失败"));

            String sql = "SELECT * FROM bysj.school WHERE id = ?";
            try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
                pstmt.setLong(1, id);
                ResultSet rs = pstmt.executeQuery();

                if (rs.next()) {
                    School school = new School(
                            rs.getLong("id"),
                            rs.getString("description"),
                            rs.getString("no"),
                            rs.getString("remarks")
                    );
                    System.out.println("[DEBUG] 查询结果: " + school);
                    return school;
                }
                System.out.println("[DEBUG] 未查询到数据");
                return null;
            }
        } finally {
            JdbcHelper.close(connection);
        }
    }


    @Override
    public Collection<School> findAll() throws SQLException, BysjException {
        //创建集合类对象，用来保存所有记录代表的School对象
        //TreeSet按compare(Object o)方法指定的顺序排序
        Collection<School> desiredSchools = new TreeSet<School>();
        //获取数据库连接
        Connection connection = JdbcHelper.getConn();

        //创建查询School的主语句
        StringBuilder sql_select = new StringBuilder("SELECT * FROM School ");

        PreparedStatement pstmt_select_all =
                connection.prepareStatement(sql_select.toString());
        //执行预编译语句，结果集保存在resultSet中
        ResultSet resultSet = pstmt_select_all.executeQuery();
        //遍历resultSet
        while (resultSet.next()) {
            //获得school表中当前记录的id字段的值
            Long id = resultSet.getLong("id");
            String description = resultSet.getString("description");
            String no = resultSet.getString("no");
            String remarks = resultSet.getString("remarks");
            //以当前记录的各个字段值为参数，创建School对象
            School desiredSchool = new School(id, description, no, remarks);
            //将当前记录代表的School对象添加到desiredSchools中
            desiredSchools.add(desiredSchool);
        }
        JdbcHelper.close(resultSet, pstmt_select_all, connection);
        return desiredSchools;
    }


    public boolean update(Connection connection, School school) throws SQLException {

        //准备预编译的语句
        String sql_update = "UPDATE school SET description = ?, no = ?, remarks = ? WHERE id = ?";
        PreparedStatement pstmt_update =
                connection.prepareStatement(sql_update);

        pstmt_update.setString(1, school.getDescription());
        pstmt_update.setString(2, school.getNo());
        pstmt_update.setString(3, school.getRemarks());
        pstmt_update.setLong(4, school.getId());

        //执行预编译语句，影响的行数保存在rowAffected中
        int rowAffected = pstmt_update.executeUpdate();

        JdbcHelper.close(pstmt_update, connection);
        return rowAffected > 0;
    }

    public boolean add(Connection connection, School school) throws SQLException {
        //准备预编译的语句
        String sql_insert = "INSERT INTO school (description, no, remarks) VALUES (?, ?, ?)";
        PreparedStatement pstmt_update = connection.prepareStatement(sql_insert);

        pstmt_update.setString(1, school.getDescription());
        pstmt_update.setString(2, school.getNo());
        pstmt_update.setString(3, school.getRemarks());

        //执行预编译语句，影响的行数保存在rowAffected中
        int rowAffected = pstmt_update.executeUpdate();
        return rowAffected > 0;
    }

    public boolean delete(Integer id) throws SQLException {
        //获取数据库连接
        Connection connection = JdbcHelper.getConn();
        //准备预编译的语句
        String sql_delete_id = "DELETE FROM school WHERE id = ?";
        PreparedStatement pstmt_delete =
                connection.prepareStatement(sql_delete_id);

        pstmt_delete.setInt(1, id);

        //执行预编译语句，影响的行数保存在rowAffected中
        int rowAffected = pstmt_delete.executeUpdate();

        JdbcHelper.close(pstmt_delete, connection);
        return rowAffected > 0;
    }

    @Override
    public Collection<School> findAll(Pagination pagination) throws SQLException, BysjException {
        Collection<School> desiredSchools = new HashSet<School>();
        Connection connection = JdbcHelper.getConn();
        StringBuilder sql_select = new StringBuilder("SELECT * FROM school");
        int totalNum = CommonDao.getInstance().count(connection,"School" );
        if (pagination != null){
            String limitClause = pagination.toLimitClause(totalNum);
            sql_select.append(limitClause);
        }

        PreparedStatement pstmt = connection.prepareStatement(sql_select.toString());
        ResultSet resultSet = pstmt.executeQuery();
        while (resultSet.next()) {
            Long id = resultSet.getLong("id");
            String description = resultSet.getString("description");
            String no = resultSet.getString("no");
            String remarks = resultSet.getString("remarks");
            School desiredSchool = new School(id, description, no, remarks);
            desiredSchools.add(desiredSchool);
        }
        JdbcHelper.close(resultSet,pstmt,connection);

        return desiredSchools;
    }
}
